//
//  GDLogViewController.m
//  GuiderHealth
//
//  Created by zyming on 2022/4/28.
//  Copyright © 2022 YM&EF. All rights reserved.
//

#import "GDLogViewController.h"
#import "GDLog.h"
#import "BaseToolsKit.h"


@interface GDLogViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *baseTableView;
@property (nonatomic, strong) NSArray *dataSource;

@end

@implementation GDLogViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"LogList";
    [self setupView];
    [self.baseTableView reloadData];
}

- (void)setupView{
    self.baseTableView = [self.view createUITableViewWithBackgroudColor:UIColor.clearColor andTableViewStyle:UITableViewStylePlain andSeparatorColor:UIColor.clearColor andSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _baseTableView.frame = CGRectMake(0, SafeAreaNavBarHeight, KSCREEN_width, KSCREEN_height-SafeAreaNavBarHeight);
    _baseTableView.delegate = self;
    _baseTableView.dataSource = self;
    self.baseTableView.backgroundColor = myBGViewColor;
    self.baseTableView.rowHeight = 50;
    self.baseTableView.height = KSCREEN_height-SafeAreaNavBarHeight-SafeAreaTabbarHeight;
    [self.baseTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KSCREEN_width, 40)];
    headerView.backgroundColor = UIColor.whiteColor;
    UILabel *titleLabel = [headerView createUILabelWithBackgroudColor:UIColor.clearColor andNumberOfLines:1 andTextColor:MyTitleTextColor andFont:Font16 andTextAlignment:NSTextAlignmentLeft andText:@"FileLogSwitch"];
    [titleLabel sizeToFit];
    titleLabel.x = 17;
    titleLabel.centerY = 20;
    
    UISwitch *logEnable = [[UISwitch alloc] init];
    logEnable.x = titleLabel.maxX +20;
    logEnable.centerY = 20;
    [headerView addSubview:logEnable];
    [logEnable setOn:[GDLog getFileLogOnOrOff]];
    [logEnable addTarget:self action:@selector(logEnableAction:) forControlEvents:UIControlEventValueChanged];
    
    [headerView createRowLineViewWithBackgroudColor:myLineColor andX:0 andY:43.5 andWidth:KSCREEN_width];
    return headerView;
}
- (void)logEnableAction:(UISwitch *)sender{
    [GDLog setFileLogOnOrOff:sender.isOn];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"CELL"];
    RemoveAll(cell.contentView);
    cell.backgroundColor = [UIColor whiteColor];
    cell.contentView.backgroundColor = UIColor.whiteColor;
    
    NSString  *fileName = self.dataSource[indexPath.row];
    
    cell.textLabel.text = [fileName componentsSeparatedByString:@"."].firstObject;

    UIButton *moreBtn = [cell.contentView createUIButtonWithAlignment:0 andTitleColor:MyTitleTextColor andTitle:@"More"];
    moreBtn.tag = indexPath.row;
    moreBtn.frame = CGRectMake(KSCREEN_width-60, 0, 50, 50);
    [moreBtn addTarget:self action:@selector(moreBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)moreBtnAction:(UIButton *)sender{
    
    [self alertViewActionWithIndex:sender.tag];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
}

- (void)alertViewActionWithIndex:(NSInteger )index{
    
    NSString  *fileName = self.dataSource[index];
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Tips" message:nil preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *shareAction = [UIAlertAction actionWithTitle:@"share" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了分享");
//        [self shareLogContent:logModel.content];
//        [self writeFile:logModel.time content:logModel.content];
        
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.log",fileName]];
        [self shareLogContent:filePath];
    }];
    [alertController addAction:shareAction];
    
    UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:@"delete" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了删除");
       
        
        NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:fileName];
        BOOL isSuccess = [GDLog removeFileWithPath:filePath];
        if (isSuccess) {
            NSMutableArray *mutArray = self.dataSource.mutableCopy;
            [mutArray removeObjectAtIndex:index];
            self.dataSource = mutArray.copy;
            [self.baseTableView reloadData];
        }
    }];
    [alertController addAction:deleteAction];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"cancel" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"点击了取消");
    }];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)writeFile:(NSString *)file content:(NSString *)content{
    
    // 名称自定义,上传服务器的时候关联userId就可以, 便于下载
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.log",file]];
    NSError *error = nil;
    [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        NSLog(@"文件写入失败 errorInfo: %@", error.domain);
    }else{
        NSLog(@"filePath:%@",filePath);
        [self shareLogContent:filePath];
    }

    
    
//    NSFileManager *fileManager = [NSFileManager defaultManager];
    // 如果不存在
//    if(![fileManager fileExistsAtPath:filePath]) {
//        [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
//        if (error) {
//            NSLog(@"文件写入失败 errorInfo: %@", error.domain);
//        }
//    }
//    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
//    [fileHandle seekToEndOfFile];
//    NSData* stringData  = [content dataUsingEncoding:NSUTF8StringEncoding];
//    [fileHandle writeData:stringData]; // 追加
//    [fileHandle synchronizeFile];
//    [fileHandle closeFile];
}
-(NSString *)readFile{

     //创建文件管理器

      NSFileManager *fileManager = [NSFileManager defaultManager];

      //获取路径

      //参数NSDocumentDirectory要获取那种路径

      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

     NSString *documentsDirectory = [paths objectAtIndex:0];//去处需要的路径

     //更改到待操作的目录下

     [fileManager changeCurrentDirectoryPath:[documentsDirectory stringByExpandingTildeInPath]];

      //获取文件路径

      NSString *path = [documentsDirectory stringByAppendingPathComponent:@"username"];

      NSData *reader = [NSData dataWithContentsOfFile:path];

      return [[NSString alloc] initWithData:reader                                  encoding:NSUTF8StringEncoding];

}

- (void)shareLogContent:(NSString *)content{
    
    NSURL *url = [NSURL fileURLWithPath:content];
    NSLog(@"url:%@",url);
    NSArray *activityItems = @[url];
        
    UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];

//    activityVC.excludedActivityTypes = @[UIActivityTypePrint, UIActivityTypeCopyToPasteboard,UIActivityTypeAssignToContact,UIActivityTypeSaveToCameraRoll];
        
    [self presentViewController:activityVC animated:YES completion:nil];
        
    //分享之后的回调
    activityVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
            //分享 成功
        } else  {
            NSLog(@"cancled");
            //分享 取消
        }
    };
}

- (NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [GDLog getLogDataInfo];
    }
    return _dataSource;
}
@end
